package com.ayu.auth.filter;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.ayu.auth.config.RsaKeyProperties;
import com.ayu.auth.pojo.SysRole;
import com.ayu.auth.pojo.SysUser;
import com.ayu.auth.util.OutPutJson;
import com.ayu.common.util.JwtUtils;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;

/**
 * @Author: 徐林玉//作者及
 * @Date: 2021/9/27//完成日期
 * @Description: //
 * @Version: v0.0.1 // 版本信息
 * @Function List: // 主要函数及其功能
 * @Others: // 其它内容的说明
 * @History: // 历史修改记录
 **/

@Data
@Slf4j
public class JwtLogFilter extends UsernamePasswordAuthenticationFilter
{

	private AuthenticationManager authenticationManager;

	private RsaKeyProperties rsaKeyProperties;

	public JwtLogFilter(AuthenticationManager authenticationManager, RsaKeyProperties rsaKeyProperties)
	{
		this.authenticationManager = authenticationManager;
		this.rsaKeyProperties = rsaKeyProperties;
	}

	@Override
	public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException
	{

		try
		{
			StringBuffer sb = new StringBuffer() ;
			ServletInputStream is = request.getInputStream();
			InputStreamReader isr = new InputStreamReader(is);
			BufferedReader br = new BufferedReader(isr);
			String s = "" ;
			while((s=br.readLine())!=null){
				sb.append(s) ;
			}
			String str =sb.toString();


			SysUser sysUser = JSONObject.parseObject(str,new TypeReference<SysUser>(){});

			UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(sysUser.getUsername(), sysUser.getPassword());

			return authenticationManager.authenticate(authRequest);

		} catch (Exception e)
		{
			OutPutJson.success(response, HttpServletResponse.SC_UNAUTHORIZED, "用户名或密码错误!");
			throw new RuntimeException(e);
		}
	}

	@Override
	protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException
	{

		SysUser sysUser = new SysUser();

		sysUser.setUsername(authResult.getName());
		//设置角色
		sysUser.setRoles((List<SysRole>) authResult.getAuthorities());

		//生成token
		String token = JwtUtils.generateTokenExpireInMinutes(sysUser, rsaKeyProperties.getPrivateKey(), 24 * 60);

		//返回token
		response.addHeader("Authorization", "Bearer " + token);
		OutPutJson.success(response, HttpServletResponse.SC_OK, "认证通过!");

	}
}
